<?php

/**
 * news actions.
 *
 * @package    bolao-aabb
 * @subpackage news
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class newsActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    if ($request->getRequestFormat() == 'atom')
    {
      $this->news_list = BolaoNewsPeer::getLastNews(sfConfig::get('app_max_news_on_feed'));
    }
    else
    {
      $this->pager = new sfPropelPager(
        'BolaoNews',
        sfConfig::get('app_max_news_per_page')
      );
      $this->pager->setCriteria(BolaoNewsPeer::getLatestNewsCriteria());
      $this->pager->setPage($request->getParameter('page', 1));
      $this->pager->init();
    }
  }

  public function executeNew(sfWebRequest $request)
  {
    $bolao_news = new BolaoNews();
    $bolao_news->setCreatorId($this->getUser()->getProfile()->getUserId());

    $this->form = new BolaoNewsForm($bolao_news);
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

    $this->form = new BolaoNewsForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $bolao_news = $this->getRoute()->getObject();

    $this->form = new BolaoNewsForm($bolao_news);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));

    $bolao_news = $this->getRoute()->getObject();

    $this->form = new BolaoNewsForm($bolao_news);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->bolao_news = $this->getRoute()->getObject();
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $bolao_news->delete();

    $this->redirect('news/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $bolao_news = $form->save();

      if ($form['send_email']->getValue())
        $this->redirect('@send_email?type=news&id='.$bolao_news->getId());
      else
        $this->redirect('news/index');
    }
  }
}
